<?php
/**
 * 
 */
class User 
{

	public $path = "./db/user.txt";
	
	public function reg()
	{
		
		include './template/reg.html';
	}

	public function loginout()
	{
		session_unset();
		session_destroy();
		header("Location:./index.php");
	}

	public function login()
	{
		$data = $_POST;

		$users = $this->get_user();

		foreach ($users as  $user) {
			if($user['username']==$data['username']&&$user['password']==md5($data['password'])){
				$_SESSION['username'] = $data['username'];
				exit(json_encode(['code'=>0,'info'=>'登录成功']));
			}
		}

		exit(json_encode(['code'=>1,'info'=>'帐号或者密码不正确']));
	}

	public function add()
	{
		$data = $_POST;

		foreach ($data as $k => $v) {
			$function = "check_".$k;
			$this->$function($v);
		}

		$data['ctime'] = time();
		$data['password'] = md5($data['password']);
		
		$users = $this->get_user();

		$users[] = $data;

		$this->put_data($users);

		exit(json_encode(['code'=>0,'info'=>'注册成功']));
		
	}

	public function put_data($data)
	{
		file_put_contents($this->path,json_encode($data));
	}

	public function check_repassword()
	{
		# code...
	}

	public function check()
	{
		$value = $_POST['value'];
		$key = "check_".$_POST['key'];
		$this->$key($value);
	}

	public function check_password($password)
	{
		$preg = "/^[a-z0-9]{6,10}$/";

		$c= preg_match($preg, $password);

		if(!$c){
			exit(json_encode(['code'=>1,'info'=>'密码格式不正确']));
		}
		if(isset($_POST['key'])){
			exit(json_encode(['code'=>0,'info'=>'密码可以用']));
		}
	}

	public function check_phone($phone)
	{
		$preg = "/^\d{11}$/";

		$c= preg_match($preg, $phone);

		if(!$c){
			exit(json_encode(['code'=>1,'info'=>'手机不正确']));
		}

		$users = $this->get_user();

		foreach ($users as  $user) {
			if($user['phone']==$phone){
				exit(json_encode(['code'=>1,'info'=>'手机已存在']));
			}
		}

		if(isset($_POST['key'])){
			exit(json_encode(['code'=>0,'info'=>'手机可以用']));
		}
		
	}

	public function check_username($username)
	{

		$preg = "/^[a-z][a-z0-9]{5,10}$/";

		$c= preg_match($preg, $username);

		if(!$c){
			exit(json_encode(['code'=>1,'info'=>'用户名必须是6-11位.....']));
		}

		$users = $this->get_user();

		foreach ($users as  $user) {
			if($user['username']==$username){
				exit(json_encode(['code'=>1,'info'=>'用户名已存在']));
			}
		}
		if(isset($_POST['key'])){
			exit(json_encode(['code'=>0,'info'=>'用户名可以用']));
		}
	}
	public function get_user()
	{
		$data = file_get_contents($this->path);

		return $data = json_decode($data,true);
	}
}